from layer import Layer
from GeomAlgo import intersectTriangleZPlane
import numpy as np


class SweepPlane:
    def __init__(self):
        self.triangles = []
        self.z = 0


class IntersectStl_sweep:
    def __init__(self, stlModel, layerThk):
        self.stlModel = stlModel
        self.layerThk = layerThk
        self.layers = []
        self.intersect()

    def intersect(self):
        triangles = self.stlModel.triangles
        triangles.sort(key=lambda t: t.zMinPnt(), reverse=False)
        zs = self.genLayerHeights()
        k = 0
        sweep = SweepPlane()
        for z in zs:
            for i in range(len(sweep.triangles) - 1, -1, -1):
                if z > sweep.triangles[i].zMaxPnt():
                    del sweep.triangles[i]
            for i in range(k, len(triangles)):
                tri = triangles[i]
                if z >= tri.zMinPnt() and z <= tri.zMaxPnt():
                    sweep.triangles.append(tri)
                elif tri.zMinPnt() > z:
                    k = i
                    break
            layer = Layer(z)
            for triangle in sweep.triangles:
                seg = intersectTriangleZPlane(triangle, z)
                if seg is not None:
                    layer.segments.append(seg)
            self.layers.append(layer)

    def genLayerHeights(self):
        xMin, xMax, yMin, yMax, zMin, zMax = self.stlModel.getBounds()
        z = zMin + self.layerThk
        zs = [i for i in np.arange(z, zMax, step=self.layerThk, dtype="float")]
        return zs
